/**
 * 作者：
 * 创建时间：2012-11-14 下午3:27:06
 */
package dragon.model.base;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import dragon.core.util.Reflect;
import dragon.core.util.StringUtils;
import dragon.model.bizObject.BizField;
import dragon.model.bizObject.BizObject;
import dragon.model.bizObject.BizProcess;
import dragon.model.bizObject.QueryField;
import dragon.model.fieldTemplate.FieldTemplate;
import dragon.model.table.DataType;
import dragon.model.table.Field;
import dragon.model.table.Table;

/**
 * 实现功能：
 */
public class Util {

	/**
	 * 日志对象
	 */
	private static Logger logger = LoggerFactory.getLogger(Util.class);

	/**
	 * 对象的字符串表示
	 * 
	 * @param obj
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String toHtmlString(Object obj) {
		if (obj == null) {
			return null;
		}
		StringBuilder result = new StringBuilder();
		if (obj instanceof Integer || obj instanceof String) {
			result.append(obj.toString());
		} else if (obj instanceof Object[]) {
			Object[] array = (Object[]) obj;
			for (Object item : array) {
				result.append(toHtmlString(item)).append("<br/><br/>");
			}
			array = null;
		} else if (obj instanceof Map) {
			Map<Object, Object> map = (Map<Object, Object>) obj;
			Set<Entry<Object, Object>> set = map.entrySet();
			Iterator<Entry<Object, Object>> it = set.iterator();
			Entry<Object, Object> entry = null;
			while (it.hasNext()) {
				entry = it.next();
				result.append("[").append(entry.getKey().toString()).append("]<br/>");
				result.append(toHtmlString(entry.getValue())).append("<br/><br/>");
			}
			entry = null;
			it = null;
			set = null;
			map = null;
		} else if (obj instanceof List) {
			List<Object> list = (List<Object>) obj;
			for (Object item : list) {
				result.append(toHtmlString(item)).append("<br/><br/>");
			}
			list = null;
		} else if (obj instanceof FieldTemplate) {
			FieldTemplate fieldTemplate = (FieldTemplate) obj;
			result.append(fieldTemplate.toHtmlString());
			fieldTemplate = null;
		} else if (obj instanceof Field) {
			Field field = (Field) obj;
			result.append(field.toHtmlString());
			field = null;
		} else if (obj instanceof Table) {
			Table table = (Table) obj;
			result.append(table.toHtmlString());
			table = null;
		} else if (obj instanceof BizField) {
			BizField bizField = (BizField) obj;
			result.append(bizField.toHtmlString());
			bizField = null;
		} else if (obj instanceof QueryField) {
			QueryField queryField = (QueryField) obj;
			result.append(queryField.toHtmlString());
			queryField = null;
		} else if (obj instanceof BizObject) {
			BizObject bizObject = (BizObject) obj;
			result.append(bizObject.toHtmlString());
			bizObject = null;
		} else if (obj instanceof BizProcess) {
			BizProcess bizProcess = (BizProcess) obj;
			result.append(bizProcess.toHtmlString());
			bizProcess = null;
		} else {
			result.append(obj.toString());
		}
		return result.toString();
	}

	/**
	 * 动态给对象的属性赋值
	 * 
	 * @param obj
	 *            待赋值的对象实例
	 * @param attribute
	 *            对象实例中待赋值的属性
	 * @param attributeValue
	 *            值
	 */
	public static void dynamicAssignment(Object obj, String attribute, String attributeValue) {

		String fieldTypeName;
		Method setMethod;
		// 通过反射为基本属性赋值
		boolean findField = false;
		boolean findMethod = false;
		java.lang.reflect.Field field = Reflect.getDeclaredField(obj.getClass(), attribute);
		if (field != null) {
			findField = true;// 找到了对应的字段

			// 通过反射找到对应的set方法
			setMethod = Reflect.getSetterMethod(obj.getClass(), field);
			if (setMethod != null) {
				findMethod = true;// 找到了对应的方法
				try {
					Object value = null;
					fieldTypeName = field.getType().getCanonicalName();
					if (fieldTypeName.endsWith("int")) {
						value = StringUtils.intValue(attributeValue);
					} else if (fieldTypeName.endsWith("java.lang.String")) {
						value = attributeValue;
					} else if (fieldTypeName.endsWith("dragon.model.table.DataType")) {
						// 如果业务字段不是来源于数据模型，给字段配置type属性是由此处解析
						value = DataType.valueOf(attributeValue.toUpperCase());
					} else {
						// TODO:更多数据类型转换
					}
					setMethod.invoke(obj, value);// 赋值
				} catch (IllegalArgumentException e) {
					logger.error(e.getMessage(), e);
				} catch (IllegalAccessException e) {
					logger.error(e.getMessage(), e);
				} catch (InvocationTargetException e) {
					logger.error(e.getMessage(), e);
				}
			}
			// if (logger.isDebugEnabled()) {
			// logger.debug(attribute + " -->对应了属性：" + fieldName + "\t 数据类型：" + field.getType().getCanonicalName() + "\t 相关方法：" + methodName + "\t value=" + attributeValue);
			// }
		}
		if (!findField || !findMethod) {
			if (logger.isDebugEnabled()) {
				logger.warn(attribute + "\t value:" + attributeValue + "\tfindField:" + findField + "\tfindMethod:" + findMethod);
			}
		}
	}
}
